package com.xinling.modules.chat.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer;
import org.springframework.web.socket.config.annotation.WebSocketTransportRegistration;
import org.springframework.web.socket.server.standard.ServletServerContainerFactoryBean;
import org.springframework.web.socket.server.support.DefaultHandshakeHandler;
import org.springframework.web.socket.server.support.HttpSessionHandshakeInterceptor;

@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
    private static final Logger logger = LoggerFactory.getLogger(WebSocketConfig.class);

    @Override
    public void configureMessageBroker(MessageBrokerRegistry config) {
        logger.info("配置WebSocket消息代理...");
        config.enableSimpleBroker("/topic");
        config.setApplicationDestinationPrefixes("/app");
        logger.info("WebSocket消息代理配置完成 - 主题前缀: /topic, 应用前缀: /app");
    }

    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        logger.info("注册WebSocket端点...");
        try {
            registry.addEndpoint("/ws")
                    .setAllowedOrigins("http://localhost:5173")
                    .addInterceptors(new HttpSessionHandshakeInterceptor())
                    .setHandshakeHandler(new DefaultHandshakeHandler())
                    .withSockJS()
                    .setClientLibraryUrl("https://cdn.jsdelivr.net/npm/sockjs-client@1/dist/sockjs.min.js")
                    .setWebSocketEnabled(true)
                    .setSessionCookieNeeded(false)
                    .setDisconnectDelay(5000)
                    .setHeartbeatTime(25000)
                    .setStreamBytesLimit(512 * 1024)
                    .setHttpMessageCacheSize(1000);
            logger.info("WebSocket端点注册完成 - 路径: /ws, 允许的源: http://localhost:5173");
        } catch (Exception e) {
            logger.error("注册WebSocket端点时发生错误: {}", e.getMessage(), e);
            throw e;
        }
    }

    @Override
    public void configureWebSocketTransport(WebSocketTransportRegistration registration) {
        logger.info("配置WebSocket传输参数...");
        registration.setMessageSizeLimit(8192)
                .setSendBufferSizeLimit(512 * 1024)
                .setSendTimeLimit(20000);
        logger.info("WebSocket传输参数配置完成 - 消息大小限制: 8KB, 发送缓冲区: 512KB, 发送超时: 20s");
    }

    @Bean
    public ServletServerContainerFactoryBean createServletServerContainerFactoryBean() {
        logger.info("创建WebSocket容器配置...");
        ServletServerContainerFactoryBean container = new ServletServerContainerFactoryBean();
        container.setMaxTextMessageBufferSize(8192);
        container.setMaxBinaryMessageBufferSize(512 * 1024);
        container.setMaxSessionIdleTimeout(60000L);
        logger.info("WebSocket容器配置完成 - 文本消息缓冲区: 8KB, 二进制消息缓冲区: 512KB, 会话超时: 60s");
        return container;
    }
} 